package com.web44.springmvc.web;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * @Title: IndexController
 * @Description:
 * @Auther: py
 * @Version: 1.0
 * @create 2024/1/15 15:38
 */
@Controller
@RequestMapping("index")
public class IndexController {

    @GetMapping("home")
    public String homeWeb(HttpServletRequest request, HttpSession session, Model model, HttpServletResponse response) {

//        request.setAttribute("req","request 域对象");
//        model.addAttribute("req2","model");
//        session.setAttribute("session","session 域对象");
        Cookie cookie = new Cookie("user","admin");
        response.addCookie(cookie);
        return "home";
    }

    @GetMapping("home2")
    public ModelAndView home2Web() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("user","admin");
        modelAndView.setViewName("home");
        return modelAndView;
    }


    /**
     * 重定向操作
     * @param request
     * @param session
     * @param model
     * @param response
     * @return
     */
    @GetMapping("home3")
    public String home3Web(HttpServletRequest request, HttpSession session, Model model, HttpServletResponse response) {
        request.setAttribute("req","request 域对象");
        model.addAttribute("req2","model");
        session.setAttribute("session","session 域对象");
        // 重定向
        return "redirect:/index/home";

    }

    /**
     * 转发操作
     * @param request
     * @param session
     * @param model
     * @param response
     * @return
     */
    @GetMapping("home4")
    public String home4Web(HttpServletRequest request, HttpSession session, Model model, HttpServletResponse response) {
        request.setAttribute("req","request 域对象");
        model.addAttribute("req2","model");
        session.setAttribute("session","session 域对象");
        // 重定向
        return "forward:/index/home";

    }

    /**
     * 获取cookie
     * @param request
     * @param session
     * @param model
     * @param response
     * @return
     */
    @GetMapping("cookie")
    @ResponseBody
    public String cookieWeb(@CookieValue(value = "user",required = false,defaultValue = "小红") String user ) {

        // 重定向
        return user;

    }


}
